package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/*
聊天室的客服端
 */
public class Client4 {
    private Socket socket;

    public Client4() {
        //初始化数据 localhost表示本机
        try {
            /*
            实例化Socket时就是与远程服务器建立连接的过程
            需要传递两个参数：
            1.服务器的ip地址，用于找到网络上对方的计算机
            2.服务端口，用于找到服务器计算机上的服务端口的应用程序
             */
            System.out.println("正在连接服务器...");
            socket = new Socket("localhost", 8088);
            System.out.println("与服务器建立连接成功！");


        } catch (IOException e) {
            //e.printStackTrace();
        }
    }

    public void start() {
        Scanner sc = new Scanner(System.in);
        try {
            //启动一个线程去接收消息

            Runnable sh = new ServerHandler(socket);
            Thread t = new Thread(sh);
            t.start();
            //发送
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw, true);
            pw.println("你好服务器");


            //pw.flush();
            while (true) {
                System.out.println("输入发送的消息");
                String s = sc.nextLine();
                if ("exit".equals(s)) {
                    pw.println("GG" + "   " + "关闭");
                    break;
                }
                pw.println(s);
                // pw.flush();
            }
            /*while ((temp = br.readLine())!=null){

                System.out.println(temp);
            }*/
            pw.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
               // e.printStackTrace();
            }
        }
    }

    class ServerHandler implements Runnable {

        private Socket socket;

        public ServerHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {

                //接收
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String temp;


                while ((temp = br.readLine()) != null) {
                    System.out.println();
                    System.out.println(temp);
                }
                br.close();
            } catch (IOException e) {
                //e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {

            Client4 client = new Client4();
            client.start();

    }
}
